<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Arr;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 返回失败
     *
     * @param string $message
     * @param int $code
     *
     * @return JsonResponse
     */
    public function error(string $message = 'An error has occurred', int $code = 400): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'message' => $message,
        ]);
    }

    /**
     * 返回成功
     *
     * @param mixed $data
     * @param array $extends
     *
     * @return JsonResponse
     */
    public function success($data = 'OK', array $extends = []): JsonResponse
    {
        $reservedKeys = ['code', 'message', 'data', 'meta', 'links'];
        $base = ['code' => 200, 'message' => is_string($data) ? $data : 'OK'];
        if ($data instanceof JsonResource) {
            $data->additional(array_merge($base, Arr::except($extends, $reservedKeys)));
            return $data->response();
        }
        return response()->json(array_merge($base, !is_string($data) ? ['data' => $data] : [], Arr::except($extends, $reservedKeys)));
    }
}
